package com.monitor.app_monitor.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.monitor.app_monitor.config.ClickHouseConfig;
import com.monitor.app_monitor.entity.*;
import com.monitor.app_monitor.mapper.CellectInfoMapper;
import com.monitor.app_monitor.mapper.ServiceListMapper;
import com.monitor.app_monitor.mapper.TableListMapper;
import com.monitor.app_monitor.service.TaskService;
import com.monitor.app_monitor.service.quartz.utils.ExecuteScript;
import com.monitor.app_monitor.service.quartz.utils.FileinfoScriptExecResult;
import com.monitor.app_monitor.service.quartz.utils.HttpClientUtil;
import com.monitor.app_monitor.service.quartz.utils.QuartzManager;
import com.monitor.app_monitor.vo.EmsListVo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {


    @Value("${fileinfo}")
    private  String fileInfoScript;

    @Value("${dataPath}")
    private String dataPath;

    @Autowired
    QuartzManager quartzManager;

    @Autowired
    ServiceListMapper serviceListMapper;

    @Autowired
    TableListMapper tableListMapper;

    @Resource
    private ClickHouseConfig clickHouseConfig;

    @Autowired
    CellectInfoMapper cellectInfoMapper;

    @Value("${fileInfoCronStr}")
    private String cronStr;

    @Resource
    private ExecuteScript executeScript;

    @Override
    public void initSchedule() throws SchedulerException {



        //添加采集程序监控
        ServiceList serviceList = new ServiceList();
        QueryWrapper<ServiceList> queryWrapper = new QueryWrapper<>(serviceList);
        List<ServiceList> serviceLists = serviceListMapper.selectList(queryWrapper);

        serviceLists.forEach(service -> {
            quartzManager.addJob(service);
        });

        //采集任务监控
        List<CellectInfo> cellectInfos = cellectInfoMapper.selectList(new QueryWrapper<>(new CellectInfo()));
        cellectInfos.forEach(cellectInfo -> {
            quartzManager.addJob(cellectInfo);
        });

        //添加一干文件大小行数监控并生成文件
        quartzManager.addJob(cellectInfos);

        //告警mysql数据
        quartzManager.addAlarmJob();

        //性能nce-s
        quartzManager.addPmNceS();

        //添加资源数据库监控  根据网管分类
        quartzManager.addTableByEmsIpJob();

        //添加更新时间标识监控
        quartzManager.addDateInfoJob();

//        //添加二干文件监控
//        quartzManager.addRGFileJob();

        //添加性能文件监控
        quartzManager.addPmFileInfo();

        //添加传输段数据
        quartzManager.addTrsSegNo();

        //添加测试任务
        quartzManager.addTestJon();



    }

    @Override
    public List<TaskDO> alljob() {
        List<TaskDO> allJob = null;
        try {
            allJob = quartzManager.getAllJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return allJob;
    }

    @Override
    public void run(String taskName, String group) throws SchedulerException {

        quartzManager.runJobNow(taskName, group);
    }

    @Override
    public String sendMsg(Webhook webhook) {
        String url = "http://10.190.3.240:2214/esb/JT.EMOS.MESSAGE.SEND/0?authcode=SlRfQ1NZR0NKI0BhdXRoQCNqV1VKbzVMMw&msgid=CSYGCJ";
        webhook.getAlerts().forEach(msg -> {
            StringBuilder msgstr = new StringBuilder();

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(System.currentTimeMillis());

            msgstr.append("时间：" + formatter.format(date));
            msgstr.append("\r\n");
            msgstr.append("状态：" + msg.getStatus());
            msgstr.append("\r\n");
            msgstr.append("标题：" + msg.getAnnotations().getTitle());
            msgstr.append("\r\n");
            msgstr.append("详细信息：" + msg.getAnnotations().getDescription());


            List<String> phones = new ArrayList<>();
            phones.add("13231230937");
            phones.add("17610161593");
            Map<String, Object> map = new HashMap<>();
            map.put("orgSystem", "JT.EMOS.MESSAGE.SEND");
            map.put("msgKey", "23233431101");
            map.put("msgType", "SMS");
            map.put("msgText", msgstr.toString());
            map.put("msgAddress", phones);
            map.put("msgLevel", "MINOR");

            String jsonString = JSONObject.toJSONString(map);

            String s = HttpClientUtil.doPostJson(url, jsonString, null);
            log.info("返回结果：{}", s);
        });


        return "ok";
    }

    @Override
    public List<EmsListVo> emsList() {
        List<CellectInfo> cellectInfos = cellectInfoMapper.selectList(new QueryWrapper<>(new CellectInfo()));
        List<EmsListVo> emsListVos = new ArrayList<>();

        List<String> emsList = new ArrayList<>();

        cellectInfos.forEach(cellectInfo -> {

            emsList.add(cellectInfo.getEmsName());
        });


        List<String> collects = emsList.stream().distinct().collect(Collectors.toList());

        collects.forEach(collect -> {
            EmsListVo emsListVo = new EmsListVo();
            emsListVo.setEmsName(collect);
            List<String> emsResList = new ArrayList<>();
            List<CellectInfo> resList = cellectInfoMapper.selectList(new LambdaQueryWrapper<>(new CellectInfo())
                    .eq(CellectInfo::getEmsName, collect));

            resList.forEach(res -> {
                emsResList.add(res.getResType());
                emsListVo.setDeployer(res.getDeveloper());
            });

            emsListVo.setResList(emsResList);
            emsListVos.add(emsListVo);
        });

        return emsListVos;
    }

    @Override
    public String emsAdd(String emsName, String resType) {
        String cellectTime = "0 0 10 * * ?";


        CellectInfo cellectInfo = cellectInfoMapper.selectOne(new LambdaQueryWrapper<>(new CellectInfo())
                .eq(CellectInfo::getEmsName, emsName)
                .last("limit 1")
        );

        cellectTime = cellectInfo.getCellectTime();

        CellectInfo NewCellectInfo = new CellectInfo();
        NewCellectInfo.setEmsName(emsName);
        NewCellectInfo.setCellectTime(cellectTime);
        NewCellectInfo.setDeveloper(cellectInfo.getDeveloper());
        NewCellectInfo.setResType(resType);


        int insert = cellectInfoMapper.insert(NewCellectInfo);

        if (insert == 1) {
            return "ok";
        }

        return "err";
    }

    @Override
    public String emsdel(String emsName, String resType) {


        int delete = cellectInfoMapper.delete(new LambdaQueryWrapper<>(new CellectInfo())
                .eq(CellectInfo::getEmsName, emsName)
                .eq(CellectInfo::getResType, resType)
        );


        if (delete == 1) {
            return "ok";
        }

        return "err";
    }

    @Override
    public String getYgFile() {
        Date date = new Date();
        String strDateFormat = "yyyyMMddHHmm";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String DataFile = sdf.format(date);


        List<CellectInfo> cellectInfos = cellectInfoMapper.selectList(new QueryWrapper<>(new CellectInfo()));

        List<FileinfoData> fileSizeinfoDataList = new ArrayList<>();
        List<FileinfoData> fileNbinfoDataList = new ArrayList<>();

        List<String> emsList = new ArrayList<>();

        cellectInfos.forEach( cellectInfo -> {
            emsList.add(cellectInfo.getEmsName());
        });

        String[] res = {"ACTNIDME","ACTNIDPTP","CC","CTP","CV","EH","EQ","FD","FDTP","MD","ME","MER","MLSN","NRO","PG","PS","PTP","RA","RO","ROCC","ROTL","ROUT","SD","SH","SNC","SNCTP","SP","TL","TR"};

        List<String> collects = emsList.stream().distinct().collect(Collectors.toList());


        collects.forEach(collect -> {

            FileinfoData fileSizeinfoData = new FileinfoData();
            FileinfoData fileNbinfoData = new FileinfoData();


            HashMap<String, String> fileSize = new HashMap<>();
            HashMap<String, String> fileNb = new HashMap<>();


            for (int i = 0; i < res.length; i++) {
                int resSizeCode = 0;
                int resNumberCode = 0;
                String SizeString = "";

                final FileinfoScriptExecResult fileinfoScriptExecResult;
                try {
                    fileinfoScriptExecResult = executeScript.executeFileInfoScript(fileInfoScript,collect,res[i],dataPath);
                    String  SizeResult = fileinfoScriptExecResult.getFileSize();
                    String  NumberResult = fileinfoScriptExecResult.getFileNb();

                    resSizeCode = Integer.valueOf(SizeResult);
                    resNumberCode = Integer.valueOf(NumberResult);

                    if (resSizeCode>1024 ) {
                        SizeString = String.valueOf(resSizeCode/1024)+"M";
                    }else {
                        SizeString = String.valueOf(resSizeCode)+"KB";
                    }


                    fileSize.put(res[i],SizeString);
                    fileNb.put(res[i],String.valueOf(resNumberCode)+"行");

                } catch (Exception e) {

                }
            }

            fileSizeinfoData.setEmsName(collect);
            fileSizeinfoData.setACTNIDME(fileSize.get(res[0]));
            fileSizeinfoData.setACTNIDPTP(fileSize.get(res[1]));
            fileSizeinfoData.setCC(fileSize.get(res[2]));
            fileSizeinfoData.setCTP(fileSize.get(res[3]));
            fileSizeinfoData.setCV(fileSize.get(res[4]));
            fileSizeinfoData.setEH(fileSize.get(res[5]));
            fileSizeinfoData.setEQ(fileSize.get(res[6]));
            fileSizeinfoData.setFD(fileSize.get(res[7]));
            fileSizeinfoData.setFDTP(fileSize.get(res[8]));
            fileSizeinfoData.setMD(fileSize.get(res[9]));
            fileSizeinfoData.setME(fileSize.get(res[10]));
            fileSizeinfoData.setMER(fileSize.get(res[11]));
            fileSizeinfoData.setMLSN(fileSize.get(res[12]));
            fileSizeinfoData.setNRO(fileSize.get(res[13]));
            fileSizeinfoData.setPG(fileSize.get(res[14]));
            fileSizeinfoData.setPS(fileSize.get(res[15]));
            fileSizeinfoData.setPTP(fileSize.get(res[16]));
            fileSizeinfoData.setRA(fileSize.get(res[17]));
            fileSizeinfoData.setRO(fileSize.get(res[18]));
            fileSizeinfoData.setROCC(fileSize.get(res[19]));
            fileSizeinfoData.setROTL(fileSize.get(res[20]));
            fileSizeinfoData.setROUT(fileSize.get(res[21]));
            fileSizeinfoData.setSD(fileSize.get(res[22]));
            fileSizeinfoData.setSH(fileSize.get(res[23]));
            fileSizeinfoData.setSNC(fileSize.get(res[24]));
            fileSizeinfoData.setSNCTP(fileSize.get(res[25]));
            fileSizeinfoData.setSP(fileSize.get(res[26]));
            fileSizeinfoData.setTL(fileSize.get(res[27]));
            fileSizeinfoData.setTR(fileSize.get(res[28]));


            fileNbinfoData.setEmsName(collect);
            fileNbinfoData.setACTNIDME(fileNb.get(res[0]));
            fileNbinfoData.setACTNIDPTP(fileNb.get(res[1]));
            fileNbinfoData.setCC(fileNb.get(res[2]));
            fileNbinfoData.setCTP(fileNb.get(res[3]));
            fileNbinfoData.setCV(fileNb.get(res[4]));
            fileNbinfoData.setEH(fileNb.get(res[5]));
            fileNbinfoData.setEQ(fileNb.get(res[6]));
            fileNbinfoData.setFD(fileNb.get(res[7]));
            fileNbinfoData.setFDTP(fileNb.get(res[8]));
            fileNbinfoData.setMD(fileNb.get(res[9]));
            fileNbinfoData.setME(fileNb.get(res[10]));
            fileNbinfoData.setMER(fileNb.get(res[11]));
            fileNbinfoData.setMLSN(fileNb.get(res[12]));
            fileNbinfoData.setNRO(fileNb.get(res[13]));
            fileNbinfoData.setPG(fileNb.get(res[14]));
            fileNbinfoData.setPS(fileNb.get(res[15]));
            fileNbinfoData.setPTP(fileNb.get(res[16]));
            fileNbinfoData.setRA(fileNb.get(res[17]));
            fileNbinfoData.setRO(fileNb.get(res[18]));
            fileNbinfoData.setROCC(fileNb.get(res[19]));
            fileNbinfoData.setROTL(fileNb.get(res[20]));
            fileNbinfoData.setROUT(fileNb.get(res[21]));
            fileNbinfoData.setSD(fileNb.get(res[22]));
            fileNbinfoData.setSH(fileNb.get(res[23]));
            fileNbinfoData.setSNC(fileNb.get(res[24]));
            fileNbinfoData.setSNCTP(fileNb.get(res[25]));
            fileNbinfoData.setSP(fileNb.get(res[26]));
            fileNbinfoData.setTL(fileNb.get(res[27]));
            fileNbinfoData.setTR(fileNb.get(res[28]));



            fileSizeinfoDataList.add(fileSizeinfoData);
            fileNbinfoDataList.add(fileNbinfoData);

        });


        ExcelWriter excelWriter = EasyExcel.write("/home/deployer/openresty/nginx/html/cellect-download/FileSize"+DataFile+".xlsx").build();

        WriteSheet writeSheet = EasyExcel.writerSheet(0, "文件大小").head(FileinfoData.class).build();
        excelWriter.write(fileSizeinfoDataList, writeSheet);


        writeSheet = EasyExcel.writerSheet(1, "文件行数").head(FileinfoData.class).build();
        excelWriter.write(fileNbinfoDataList, writeSheet);
        //千万别忘记finish 会帮忙关闭流
        excelWriter.finish();

        return "http://10.170.66.24:10133/cellect-download/FileSize"+DataFile+".xlsx";
    }


}
